#!/usr/bin/env python
#coding=utf-8
import time
import pyDes#可逆加密算法
import pickle
import urllib
import hashlib   
import random
import os

class Tools():

    ##########保存文件#########################
    @staticmethod
    def saveData(filename, data): 
        '''save data to filename in pickle format
        '''
        f = open(filename, 'wb')
        pickle.dump(data, f)
        f.close()   
    
    @staticmethod    
    def loadData(filename): 
        '''pickle load from filename
        '''
        try:
            f = open(filename, 'rb')
            data = pickle.load(f)
            f.close() 
            return data 
        except:
            return 0
        
    @staticmethod
    def saveToFile(filename, data, dataInfo=''):
        '''保存为文本文件，不用写扩展名,dataInfo是额外信息
        '''
        f = open('%s.txt' % filename, 'w')
        if dataInfo:
            f.write(dataInfo + '\n')
            f.write('#'*20 + '\n')
        f.write(data)    
        f.close()
    
    ###########编码转换#####################        
    @staticmethod
    def unicodeToHanzi(unicode):  
        '''
        >>> print Tools.unicodeToHanzi('\u4f60\u597d')
        你好
        '''      
        s = "u'%s'" % unicode
        return eval(s)   
    
    @staticmethod     
    def unicodeToHanzi_special(s):
        '''
        >>> s='&#x60A8;&#x7684;&#x5361;&#x69FD;&#x53EF;&#x80FD;&#x4E0D;&#x4E3A;&#x7A7A;&#xFF0C;&#x8BF7;&#x5237;&#x65B0;&#x9875;&#x9762;&#x518D;&#x8BD5;&#x3002'
        >>> print Tools.unicodeToHanzi_special(s)
        您的卡槽可能不为空，请刷新页面再试。
        '''
        return eval("u'%s'" % ''.join(['\u%s' % i[3:] for i in s.split(';')]))
            
    @staticmethod 
    def UTF8ToHanzi(s):
        '''
        >>> Tools.UTF8ToHanzi('\xe4\xbd\xa0\xe5\xa5\xbd')
        u'\u4f60\u597d'
        '''
        return s.decode('utf8')

    @staticmethod  
    def desEncrypt(str):
        '''自定义可逆加密
        >>> print Tools.desEncrypt('china')
        \xa2Nr\xa6\x01\x95\xd3\x1f
        '''
        k = pyDes.des("MyDESKey")  
        return k.encrypt(str, " ")
    
    @staticmethod
    def desDecrypt(str):
        '''自定义可逆解密
        >>> Tools.desDecrypt('\xa2Nr\xa6\x01\x95\xd3\x1f')
        'china'
        '''
        k = pyDes.des("MyDESKey")  
        return k.decrypt(str, " ")
    
    @staticmethod
    def urlEncode(str):
        '''url加密
        >>> Tools.urlEncode('登录')
        '%E7%99%BB%E5%BD%95'
        '''
        return urllib.quote_plus(str.encode('utf-8'))
    
    @staticmethod
    def urlDecode(str):
        '''url解密
        >>> print Tools.urlDecode('%E7%99%BB%E5%BD%95')
        登录
        '''
        return urllib.unquote_plus(str)
    
    ########其他################################  
    @staticmethod
    def makeYYTime():
        '''YY365专用
        将当前时间转化为特殊表示形式
        形如Tue%20Jul%2020%202010%2019:07:15%20GMT+0800%20(CST)
        '''
        str = time.strftime("%a %b %d %Y %H:%M:%S", time.localtime()) 
        str = str.replace(' ', '%20')
        str += '%20GMT+0800%20(CST)'
        return str    
    
    @staticmethod
    def timestampToShowTime(timestamp):
        '''返回时间戳的可视化时间
        >>> Tools.timestampToShowTime(1277002378)
        '2010-06-20 10:52:58'
        '''
        if isinstance(timestamp, (int, float)):
            return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
        else:
            return 'timestamp show be float type '
        
    @staticmethod
    def createTimeStamp():
        '''生成当前时间的时间戳
        >>> timestamp=Tools.createTimeStamp()
        >>> isinstance(timestamp,(int,float))
        True
        '''
        return time.time()
        
    @staticmethod
    def createMD5(s):  
        '''create md5 from string
        >>> Tools.createMD5('china')
        '8a7d7ba288ca0f0ea1ecf975b026e8e1'
        ''' 
        return hashlib.md5(s).hexdigest()
    
    @staticmethod   
    def getFatherDir():
        '''
        >>> Tools.getFatherDir()
        '/home/lxd/workspace/yy/src'
        '''
        return os.path.dirname(os.path.dirname(__file__))
        
    #######get random###############################
    @staticmethod
    def getRandomWord():
        '''
        >>> word=Tools.getRandomWord()
        >>> len(word)>=6 and len(word)<=9 and isinstance(word,str)
        True
        '''
        randomLen = random.randint(6, 9)
        return ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', randomLen))
    
    @staticmethod
    def getRandomNum():
        '''
        >>> word=Tools.getRandomNum()
        >>> len(word)>=6 and len(word)<=9 and isinstance(word,str)
        True
        '''
        randomLen = random.randint(6, 9)
        return ''.join(random.sample('0123456789', randomLen))
    
    @staticmethod    
    def getRandomEmail(name):
        '''
        >>> word=Tools.getRandomEmail('1')
        >>> word[:2]
        '1@'
        '''        
        email = ['qq.com', '163.com', '126.com', 'sina.com', 'gmail.com', 'sohu.com']
        return '%s@%s' % (name, random.choice(email))
    
    @staticmethod
    def getRandomCity():        
        country_file = os.path.join(Tools.getFatherDir(), 'db', 'country')
        countries = Tools.loadData(country_file)
        if countries:
            countryIds = [country['id'] for country in countries]
            return random.choice(countryIds)
        else:
            return ''
        
    @staticmethod
    def getRandomName():
        name_file = os.path.join(Tools.getFatherDir(), 'db', 'name')
        names = Tools.loadData(name_file)
        if names:
            return random.choice(names)
        else:
            return ''        
    
    @staticmethod
    def getRandomSex():
        return random.randint(1, 2)
    
if __name__ == '__main__':
#    import doctest
#    doctest.testmod()
#    print Tools.unicodeToHanzi('\u9A8C\u8BC1\u7801\u6709\u8BEF\uFF01')
    print Tools.urlEncode('@')






